"use strict";

const Controller = require("egg").Controller;

class StudentController extends Controller {
    async index() {
        const res = await this.service.student.readList();
        this.ctx.body = {
            code: 200,
            data: res,
            message: "请求成功",
        };
    }

    async create() {
        // 解析请求体
        const {
            student_name,
            student_password,
            student_code,
            grade_id,
        } = this.ctx.request.body;
        // 校验班级号
        const grade = await this.service.grade.find(grade_id);
        if (!grade) {
            this.ctx.body = {
                code: 404,
                message: "班级不存在",
            };
            return;
        }
        // 入库
        const res = await this.service.student.add({
            student_name,
            student_password,
            student_code,
            grade_id,
        });
        // 响应
        if (res.affectedRows === 1) {
            this.ctx.body = {
                code: 201,
                message: "添加成功",
            };
        }
    }
}

module.exports = StudentController;
